const Koa = require("koa");

const Router = require("@koa/router");
const cors = require("koa-cors");

const app = new Koa();

const router = new Router();
const { koaBody } = require("koa-body");
const koaStatic = require("koa-static");
const fs = require("fs");
const path = require("path");

app.use(cors());
app.use(koaStatic(path.join(__dirname, "./upload")));

app.use(koaBody({
    multipart:true
}));




router.post("/api/upload", async ctx => {
    //  先获取参数
    const files = ctx.request.files.file;
    const filename = +new Date() + files.originalFilename;
    //  创建可读流
    const rs = fs.createReadStream(files.filepath);
    //  创建可写流
    const ws = fs.createWriteStream("./upload/"+filename);
    //  通过管道符输出
    rs.pipe(ws);
    ctx.body = {
        code:1,
        msg:"本地上传成功",
        url:`http://localhost:9000/${filename}`
    }

})



app.use(router.routes());
app.listen(9000 , () => {
    console.log(`port:9000`)
})